/**
 * 
 */
package soa.security.web.action;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

import soa.security.domain.Organization;
import soa.security.web.support.action.LdapModelAction;

/**
 * @author Cre.Gu
 *
 */
public class OrganizationAction extends LdapModelAction<Organization> {

	private static final long serialVersionUID = -822135960769317480L;

	private String organizationUid;
	private String pid;
	private String regionDn;

	public String grid() {
		if (StringUtils.isBlank(regionDn) && StringUtils.isBlank(pid))
			return SUCCESS;

		if (StringUtils.isNotBlank(regionDn))
			updateResultContent(organizationMgrService.allOrganizations(
					regionDn, buildContext().getParameters()));
		else {
			List<Organization> list = new ArrayList<Organization>();
			list.add(organizationMgrService.findByDn(parentDn));

			list.addAll(organizationMgrService.allSubOrganizations(pid,
					buildContext().getParameters()));

			updateResultContent(list);
		}
		return SUCCESS;
	}

	public String edit() {
		Organization organization = getModel();
		if (StringUtils.isBlank(organization.getBid())) {
			organization.setBid("OR"
					+ organizationMgrService.findMaxNumber(Organization.class));

			organization.setParent(getOrganization(pid));
		}

		updateResultContent(organization);

		this.pageResult.addData("regionDn", regionDn);
		this.pageResult.addData("pid", pid);

		return SUCCESS;
	}

	public String doneSave() {
		if (StringUtils.isBlank(pid))
			organizationMgrService.addOrganization(regionDn, getModel());
		else
			organizationMgrService.addSubOrganization(pid, getModel());
		return SUCCESS;
	}

	public String doneUpdate() {
		organizationMgrService.updateOrganization(getModel());
		return SUCCESS;
	}

	public String getOrganizationUid() {
		return organizationUid;
	}

	public void setOrganizationUid(String organizationUid) {
		this.organizationUid = organizationUid;
	}

	public String getPid() {
		return pid;
	}

	public void setPid(String pid) {
		this.pid = pid;
	}

	public String getRegionDn() {
		return regionDn;
	}

	public void setRegionDn(String regionDn) {
		this.regionDn = regionDn;
	}

	@Override
	protected Organization findByDn(String dn) {
		return organizationMgrService.findByDn(dn);
	}
}
